package edu.nf.takeoutdemo.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import edu.nf.takeoutdemo.commons.config.RabbitConfig;
import edu.nf.takeoutdemo.commons.context.BaseContext;
import edu.nf.takeoutdemo.commons.result.PageResult;
import edu.nf.takeoutdemo.commons.utils.WeChatPayUtil;
import edu.nf.takeoutdemo.mapper.*;
import edu.nf.takeoutdemo.model.converter.OrderConverter;
import edu.nf.takeoutdemo.model.converter.OrderDetailConverter;
import edu.nf.takeoutdemo.model.dto.*;
import edu.nf.takeoutdemo.model.entity.*;
import edu.nf.takeoutdemo.model.vo.OrderPaymentVO;
import edu.nf.takeoutdemo.model.vo.OrderStatisticsVO;
import edu.nf.takeoutdemo.model.vo.OrderSubmitVO;
import edu.nf.takeoutdemo.model.vo.OrderVO;
import edu.nf.takeoutdemo.service.OrderService;
import edu.nf.takeoutdemo.web.websocket.WebSocketServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @author zjl
 * @date 2025/10/30
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;

    private final OrderDetailMapper orderDetailMapper;

    private final AddressBookMapper addressBookMapper;

    private final ShoppingCartMapper shoppingCartMapper;

    private final OrderConverter  orderConverter;

    private final OrderDetailConverter orderDetailConverter;

    private final UserMapper userMapper;

    private final WeChatPayUtil weChatPayUtil;

    private final RabbitTemplate  rabbitTemplate;

    private final WebSocketServer  webSocketServer;

    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrderSubmitDTO orderSubmitDTO) {
        //处理各种业务异常（地址为空，购物车为空）
        AddressBook addressBook = addressBookMapper.getById(orderSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new RuntimeException("用户地址为空，不能下单");
        }
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new RuntimeException("购物车为空，不能下单");
        }
        //向订单表插入一条数据
        Orders orders = orderConverter.toOrders(orderSubmitDTO);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());
        orderMapper.add(orders);
        //向订单明细表插入多条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart :shoppingCartList){
            OrderDetail orderDetail = orderDetailConverter.toOrderDetail(cart);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.addBatch(orderDetailList);
        //清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);
        //封装VO返回结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        //发送延迟消息
        sendDelayMessage(orders.getNumber());
//        Map<String,Object> map = new HashMap<>();
//        map.put("type",1);//表示来单提醒 2表示客户催单
//        map.put("orderId",orders.getId());
//        map.put("content","订单号"+orders.getNumber());
//
//        String json = JSON.toJSONString(map);
//        webSocketServer.sendToAllClient(json);
        return orderSubmitVO;
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                ordersPaymentDTO.getAmount(), //支付金额，单位 元
                "校园外卖", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new RuntimeException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;

    }

    @Override
    public void paySuccess(String outTradeNo) {
        Orders ordersDB =  orderMapper.getByNumber(outTradeNo);
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayStatus(Orders.PAID);
        orders.setPayMethod(1);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orderMapper.update(orders);

        //通过websocket来向客户端和服务端浏览器推送消息 type orderId content
        Map<String,Object> map = new HashMap<>();
        map.put("type",1);//表示来单提醒 2表示客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号"+outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public void reminder(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new RuntimeException("订单不存在");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号："+orders.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }

    @Override
    public void cancelOrder(OrderCancelDTO orderCancelDTO) throws Exception {
        Orders orders = orderMapper.getById(orderCancelDTO.getId());

        Integer payStatus = orders.getPayStatus();

        if (payStatus.equals(Orders.PAID)) {
            String refund = weChatPayUtil.refund(orders.getNumber(),
                    orders.getNumber(),
                    orders.getAmount(),
                    orders.getAmount());
            log.info("申请退款:{}",refund);
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(orderCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public OrderVO getDetails(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList =  orderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void repetition(Long id) {
        Long userId = BaseContext.getCurrentId();
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());
        // 将购物车对象批量添加到数据库
        shoppingCartMapper.addBatch(shoppingCartList);
    }

    @Override
    public PageResult pageQueryUser(int pageNum, int pageSize, Integer payStatus) {
        //设置分页
        PageHelper.startPage(pageNum, pageSize);
        OrderPageQueryDTO ordersPageQueryDTO = new OrderPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setPayStatus(payStatus);

        //分页查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();

        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long ordersId = orders.getId();
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(ordersId);
                OrderVO vo = new OrderVO();
                BeanUtils.copyProperties(orders,vo);
                vo.setOrderDetailList(orderDetailList);
                list.add(vo);
            }
        }
        PageResult pageResult = new PageResult(page.getTotal(), list);
        return pageResult;
    }

    @Override
    public void cancelUserOrder(Long id) throws Exception {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new RuntimeException("订单不存在");
        }
        if (orders.getPayStatus().equals(Orders.PAID)) {
            String refund = weChatPayUtil.refund(orders.getNumber(),
                    orders.getNumber(),
                    orders.getAmount(),
                    orders.getAmount());
            log.info("申请退款:{}",refund);
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void confirmOrder(OrderConfirmDTO orderConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(orderConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    @Override
    public void rejectionOrder(OrderRejectionDTO orderRejectionDTO) throws Exception {
        Orders orders = orderMapper.getById(orderRejectionDTO.getId());
        if (orders==null||!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new RuntimeException("订单状态错误");
        }

        if (orders.getPayStatus().equals(Orders.PAID)) {
            String refund = weChatPayUtil.refund(orders.getNumber(),
                    orders.getNumber(),
                    orders.getAmount(),
                    orders.getAmount());
            log.info("申请退款:{}",refund);
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setId(orders.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(orderRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void completeOrder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders==null||!orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new RuntimeException("订单状态错误");
        }
        orders.setId(orders.getId());
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void deliveryOrder(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders==null||!orders.getStatus().equals(Orders.CONFIRMED)) {
            throw new RuntimeException("订单状态错误");
        }
        orders.setId(orders.getId());
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    @Override
    public PageResult conditionSearch(OrderPageQueryDTO orderPageQueryDTO) {
        PageHelper.startPage(orderPageQueryDTO.getPageNum(), orderPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(orderPageQueryDTO);
        List<OrderVO> orderVOList = getOrderVOList(page);
        PageResult pageResult = new PageResult(page.getTotal(), orderVOList);
        return pageResult;
    }

    @Override
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed  =  orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed  =  orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress  =  orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);
                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }
    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 延迟投递消息
     * @param orderNumber
     */
    private void sendDelayMessage(String orderNumber) {
        CorrelationData cdata = new CorrelationData(UUID.randomUUID().toString());
        //延迟发送
        rabbitTemplate.convertAndSend(RabbitConfig.DELAY_EXCHANGE,
                RabbitConfig.DELAY_KEY, orderNumber, messageSourceProcessor -> {
                    //设置延迟时间
                    messageSourceProcessor.getMessageProperties().setDelayLong(RabbitConfig.DELAY_TIME);
                    //返回这个消息处理器
                    return messageSourceProcessor;
                }, cdata);
    }
}
